#include "Tp2.h"

Tp2::Tp2(HINSTANCE hInstance, std::string winCaption)
	: D3DApp(hInstance, winCaption, D3DDEVTYPE_HAL, D3DCREATE_HARDWARE_VERTEXPROCESSING),
	hexalactere(0),
	trilatere(0)
{
	InitAllVertexDeclaration();
	GenerateLevel(); 
	//trilatere = new Triangle();
	hexalactere = new Cube();
	m_Collision = false;
	
	//grid = new TriGrid(10, 10, 1, 1);
	SetCameraPosition(0, 0, 50);
	OnResetDevice();
}

Tp2::~Tp2()
{
	DestroyAllVertexDeclaration();
	delete trilatere;
	delete hexalactere;
	
}

void Tp2::OnLostDevice()
{
	D3DApp::OnLostDevice();
}

void Tp2::OnResetDevice()
{
	D3DApp::OnResetDevice();

	HR(gD3DDevice->SetRenderState(D3DRS_LIGHTING, false));
	HR(gD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE));

	// pour le Alpha
	HR(gD3DDevice->SetRenderState(D3DRS_ALPHAREF, 10));
	HR(gD3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER));

	// alpha blend
	HR(gD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE));
	HR(gD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1));
	HR(gD3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA));
	HR(gD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA));
}
//update par frame
void Tp2::Update(double dt)
{
	D3DApp::Update(dt);
	 //timer after each dead
	if (m_Timer)
	{
		m_Time -= dt;
		if (m_Time <= 0)
		{
			Unvulnerability();
		}
	}

	//if not dead
	if (m_Life > 0)
	{
		std::cout << m_Life << std::endl;
		//check collision
		if (m_Collision)
		{
			hexalactere->MyShipPosition(D3DXVECTOR3(-100, 0, 0));
			m_Timer = true;
		}
		else
		{   
			OnCollision();
			
		}
	}
	//game over
	GameOver();
	
}
//draw on scene
void Tp2::Draw(ID3DXSprite& sprite, D3DXMATRIX& view, D3DXMATRIX& proj)
{
	HR(gD3DDevice->BeginScene());

	D3DApp::Draw(sprite, view, proj);

	HR(gD3DDevice->EndScene());
	HR(gD3DDevice->Present(0, 0, 0, 0));
}
//level Generator
void Tp2::GenerateLevel()
{
	for (int i = 0; i < ENEMY_NUMBER; i++)
	{
		Enemies* e = new Enemies();
		maxEnemieList.push_back(e);
	}
	
}
//Manage the collisions
void Tp2::OnCollision()
{
	for (unsigned i = 0; i < maxEnemieList.size(); ++i)
	{
		D3DXVECTOR3 vecDist(maxEnemieList[i]->GetPosition() - hexalactere->GetPosition());
		float fDistSq(D3DXVec3Dot(&vecDist, &vecDist));
		if (fDistSq < 8)
		{
			m_Collision = true;
			std::cout << m_Collision << std::endl;
			
		}
	}
}
//timer where cube is unvulnerable after respawn
void Tp2::Unvulnerability()
{
	m_Life = m_Life - 1;
	hexalactere->MyShipPosition(D3DXVECTOR3(0, 0, 0));
	m_Collision = false;
	m_Time = 2.0f;
	m_Timer = false;
	
}
//Game Over
void Tp2::GameOver()
{
	if (m_Life == 0)
	{
		hexalactere->MyShipPosition(D3DXVECTOR3(-100, 0, 0));
		if (gDInput->keyPressed(DIK_SPACE))
		{
			hexalactere->MyShipPosition(D3DXVECTOR3(0, 0, 0));
			m_Life = 10;
		}
	}
}
